package com.xiao.blecontrol;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.*;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    //页面元素相关变量
    //输出比例进度条
    private SeekBar barOutputRatio;
    //时间（延时）进度条
    private SeekBar barTime;
    //上升误差
    private SeekBar barRisingError;
    //下降误差
    private SeekBar barDescentError;
    //采样时间
    private SeekBar barSampleTime;

    private Button connect;
    //输出比例减按钮
    private Button barOutputRatioSub;
    //输出比例加按钮
    private Button barOutputRatioPlus;
    //时间（延时）减按钮
    private Button barTimeSub;
    //时间（延时）加按钮
    private Button barTimePlus;
    //上升误差减按钮
    private Button barRisingSub;
    //上升误差加按钮
    private Button barRisingPlus;
    //下降误差减按钮
    private Button barDescentSub;
    //下降误差加按钮
    private Button barDescentPlus;
    //采样时间减按钮
    private Button barSampleTimeSub;
    //采样时间加按钮
    private Button barSampleTimePlus;

    private Button barKk2Plus;
    private Button confirm;
    private Button cancle;
    private Button search;
    private EditText connectEditText;
    //名称
    private TextView nameValue;
    //输入值
    private TextView inputValue;
    //输出值
    private TextView outputValue;
    //输出比例
    private TextView outputRatioView;

    //时间（延时）显示
    private TextView timeTextView;
    //上升误差 值
    private TextView risingErrorValue;
    //下降误差 值
    private TextView descentErrorValue;
    //采样时间
    private TextView sampleTimeValue;

    private RecyclerView rvDeviceList;
    private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1;

    private Boolean isWrite = false;

    //是否验证通过 1表示验证通过，0表示未通过
    private Integer state = 0;
    //蓝牙相关变量
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private final int REQUEST_ENABLE_BT = 1;
    private BleService mBleService;
    private BleReceiver mBleReceiver;
    private List<BluetoothDevice> mBluetoothDeviceList;
    private List<String> mRssiList;
    private DeviceListAdapter mDeviceListAdapter;

    //单选按钮
    private RadioGroup radioGroup;
    private RadioButton openLoop;
    private RadioButton closedLoop;

    private String loop = "0";
    private int timeValue = 0;
    private int risingError  = 0;
    private int descentError = 0;
    private int sampleTime = 0;
    //闭环比例
    private int closeOutputRatioValue = 1;
    //闭环比例
    private int openOutputRatioValue = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        state = 0;
        Context context = this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           startForegroundService(new Intent(context, BleService.class));
        } else {
            startService(new Intent(context, BleService.class));
        }
        //折线图
        setContentView(R.layout.activity_main);

        //名称
        //nameValue = findViewById(R.id.name_value);
        //密码
        connectEditText = findViewById(R.id.connect_edit_text);
        //输入电压
        inputValue = findViewById(R.id.input_value);
        //输出电压
        outputValue = findViewById(R.id.output_value);
        //输出比例
        outputRatioView = findViewById(R.id.output_ratio);
        barOutputRatio = findViewById(R.id.bar_output_ratio);
        barOutputRatioSub = findViewById(R.id.bar_output_ratio_sub);
        barOutputRatioPlus = findViewById(R.id.bar_output_ratio_plus);
        //时间（延时）
        timeTextView = findViewById(R.id.delay_time_value);
        barTime = findViewById(R.id.bar_time);
        barTimeSub = findViewById(R.id.bar_time_sub);
        barTimePlus = findViewById(R.id.bar_time_plus);
        //上升误差
        risingErrorValue = findViewById(R.id.rising_error_value);
        barRisingError = findViewById(R.id.bar_rising_error);
        barRisingSub = findViewById(R.id.bar_rising_sub);
        barRisingPlus = findViewById(R.id.bar_rising_plus);
        //下降误差
        descentErrorValue = findViewById(R.id.descent_error_value);
        barDescentError = findViewById(R.id.bar_descent_error);
        barDescentSub = findViewById(R.id.bar_descent_sub);
        barDescentPlus = findViewById(R.id.bar_descent_plus);
        //采样时间
        sampleTimeValue = findViewById(R.id.sample_time_value);
        barSampleTime = findViewById(R.id.bar_sample_time);
        barSampleTimeSub = findViewById(R.id.bar_sample_time_sub);
        barSampleTimePlus = findViewById(R.id.bar_sample_time_plus);

        //功能按钮
        confirm = findViewById(R.id.confirm);
        cancle = findViewById(R.id.cancle);
        //currentView = findViewById(R.id.current_value);
        search = findViewById(R.id.search);
        connect = findViewById(R.id.connect);

        radioGroup = findViewById(R.id.radioGroup);
        openLoop = findViewById(R.id.open_loop);
        closedLoop = findViewById(R.id.closed_loop);


        rvDeviceList = (RecyclerView) findViewById(R.id.rv_device_list);
        //设置按钮点击事件监听
       // connect.setOnClickListener(this);
        //输出比例
        barOutputRatioSub.setOnClickListener(this);
        barOutputRatioPlus.setOnClickListener(this);
        //时间延迟
        barTimeSub.setOnClickListener(this);
        barTimePlus.setOnClickListener(this);
        //上升误差值
        barRisingSub.setOnClickListener(this);
        barRisingPlus.setOnClickListener(this);
        //下降误差值
        barDescentSub.setOnClickListener(this);
        barDescentPlus.setOnClickListener(this);
        //采样时间
        barSampleTimeSub.setOnClickListener(this);
        barSampleTimePlus.setOnClickListener(this);

        confirm.setOnClickListener(this);
        cancle.setOnClickListener(this);
        search.setOnClickListener(this);
        connect.setOnClickListener(this);

        barTimePlus.setEnabled(false);
        barTimeSub.setEnabled(false);
        barRisingPlus.setEnabled(false);
        barRisingSub.setEnabled(false);
        barDescentPlus.setEnabled(false);
        barDescentSub.setEnabled(false);
        barSampleTimePlus.setEnabled(false);
        barSampleTimeSub.setEnabled(false);
        barTime.setEnabled(false);
        barRisingError.setEnabled(false);
        barDescentError.setEnabled(false);
        barSampleTime.setEnabled(false);
        //测试
       // String text = "535412013416B9016A00000000780D0A";
//        System.out.println(ByteUtils.isNormalDate(text));
//        String text = "535412013416B9016A00000000780D0A";
//        String ctrlStr = String.valueOf(Integer.valueOf(ByteUtils.getContorlValueStr(text),16));
//        Log.i(this.toString(), "控制返回值"+ctrlStr);
//        if(ctrlStr.equals("0")){
//            radioGroup.check(closedLoop.getId());
//        }else{
//            radioGroup.check(openLoop.getId());
//        }
//        //输出比例
//        //开环数据
//        openOutputRatioValue = Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16);
//        closeOutputRatioValue = Integer.valueOf(ByteUtils.getParamVale("close",text), 16);
//        float outputRatioValue = 1;
//        if(ctrlStr.equals("0")) {
//            outputRatioValue = ((float) closeOutputRatioValue) / 100;
//            barOutputRatio.setProgress(closeOutputRatioValue- 80);
//        }else{
//            outputRatioValue = ((float) openOutputRatioValue) / 100;
//            barOutputRatio.setProgress(openOutputRatioValue- 80);
//        }
//        outputRatioView.setText(String.valueOf(outputRatioValue));
        //String ctl = ByteUtils.getControlStr(text);
//        String input = String.valueOf(Integer.valueOf(ByteUtils.getInputValue(text),16));
//        BigDecimal inputV =  new BigDecimal(input).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
//        inputValue.setText(inputV.toString()+"V");
//        String output =String.valueOf(Integer.valueOf(ByteUtils.getOutValue(text),16));
//        BigDecimal outputV =  new BigDecimal(output).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
//        outputValue.setText(outputV.toString()+"V");
        //单选按钮
        if(openLoop.getId() == radioGroup.getCheckedRadioButtonId()){
            loop = "1";
        }else if(closedLoop.getId() == radioGroup.getCheckedRadioButtonId()){
            loop = "0";
        }
        //为RadioGroup设置监听事件
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                String sexTmp = "";
                if(checkedId == openLoop.getId()){
                    loop = "1";
                    //设置按钮不可用
                    barTimePlus.setEnabled(false);
                    barTimeSub.setEnabled(false);
                    barRisingPlus.setEnabled(false);
                    barRisingSub.setEnabled(false);
                    barDescentPlus.setEnabled(false);
                    barDescentSub.setEnabled(false);
                    barSampleTimePlus.setEnabled(false);
                    barSampleTimeSub.setEnabled(false);
                    //设置滑动条不可滑动
                    barTime.setEnabled(false);
                    barRisingError.setEnabled(false);
                    barDescentError.setEnabled(false);
                    barSampleTime.setEnabled(false);
                    //设置初始值
                    timeTextView.setText("0");
                    barTime.setProgress(0);
                    risingErrorValue.setText("0");
                    barRisingError.setProgress(0);
                    descentErrorValue.setText("0");
                    barDescentError.setProgress(0);
                    sampleTimeValue.setText("0");
                    barSampleTime.setProgress(0);
                    outputRatioView.setText(String.valueOf(((float) openOutputRatioValue) / 100));
                    barOutputRatio.setProgress(openOutputRatioValue-80);
                }else if(checkedId == closedLoop.getId()){
                    loop = "0";
                    barTimePlus.setEnabled(true);
                    barTimeSub.setEnabled(true);
                    barRisingPlus.setEnabled(true);
                    barRisingSub.setEnabled(true);
                    barDescentPlus.setEnabled(true);
                    barDescentSub.setEnabled(true);
                    barSampleTimePlus.setEnabled(true);
                    barSampleTimeSub.setEnabled(true);

                    barTime.setEnabled(true);
                    barRisingError.setEnabled(true);
                    barDescentError.setEnabled(true);
                    barSampleTime.setEnabled(true);

                    //时间
                    timeTextView.setText(String.valueOf(timeValue));
                    barTime.setProgress(timeValue);
                    //上升误差
                    risingErrorValue.setText(String.valueOf(risingError));
                    barRisingError.setProgress(risingError);
                    //下降误差
                    descentErrorValue.setText(String.valueOf(descentError));
                    barDescentError.setProgress(descentError);
                    //采样时间
                    sampleTimeValue.setText(String.valueOf(sampleTime));
                    barSampleTime.setProgress(sampleTime);

                    outputRatioView.setText(String.valueOf(((float) closeOutputRatioValue) / 100));

                    barOutputRatio.setProgress(closeOutputRatioValue-80);
                }
                Log.i("单选选中的结果:",loop);
            }
        });

        //输出比例初始化
        SeekBar.OnSeekBarChangeListener barOutputRatioListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress = progress+80;
                outputRatioView.setText(String.valueOf((float) progress / 100));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        barOutputRatio.setOnSeekBarChangeListener(barOutputRatioListener);
        //时间(延时)初始化
        SeekBar.OnSeekBarChangeListener barTimeListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                timeTextView.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        barTime.setOnSeekBarChangeListener(barTimeListener);
        //上升误差初始化
        SeekBar.OnSeekBarChangeListener barRisingErrorListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                risingErrorValue.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        barRisingError.setOnSeekBarChangeListener(barRisingErrorListener);

        //下降误差初始化
        SeekBar.OnSeekBarChangeListener barDescentErrorrListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                descentErrorValue.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        barDescentError.setOnSeekBarChangeListener(barDescentErrorrListener);
        //采样时间初始化
        SeekBar.OnSeekBarChangeListener barSampleTimeListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sampleTimeValue.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        barSampleTime.setOnSeekBarChangeListener(barSampleTimeListener);

        //初始化蓝牙
        initBle();
        initData();
        registerBleReceiver();
        local();

        //连接按钮
    }
    /**
     * 初始化蓝牙
     */
    private void initBle() {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show();
            return;
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_ENABLE_BT);
            return;
        }

        // 搜索蓝牙设备
        scanBleDevice();
        //直接连接
    }
    /**
     * 初始化数据
     */
    private void initData() {
        Log.i("main","我进来了");
        // 蓝牙设备列表
        mBluetoothDeviceList = new ArrayList<>();
        // 蓝牙设备RSSI列表
        mRssiList = new ArrayList<>();
        mDeviceListAdapter = new DeviceListAdapter(mBluetoothDeviceList, mRssiList);
        rvDeviceList.setLayoutManager(new LinearLayoutManager(this));
        rvDeviceList.setAdapter(mDeviceListAdapter);

        // 连接蓝牙设备
        mDeviceListAdapter.setOnItemClickListener(new DeviceListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this, "开始连接", Toast.LENGTH_SHORT).show();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                mBleService.connect(mBluetoothAdapter, mBluetoothDeviceList.get(position).getAddress());
            }
        });
    }
    /**
     * 搜索蓝牙设备
     */
    private void scanBleDevice() {
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mBluetoothAdapter.startLeScan(mLeScanCallback);
        // 搜索10s
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }, 10000);
    }

    /**
     * 搜索蓝牙设备回调
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
            if (!mBluetoothDeviceList.contains(bluetoothDevice)) {
                mBluetoothDeviceList.add(bluetoothDevice);
                mRssiList.add(String.valueOf(i));
                mDeviceListAdapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 注册蓝牙信息接收器
     */
    private void registerBleReceiver() {
        // 绑定服务
        Intent intent = new Intent(this, BleService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        startService(intent);

        // 注册蓝牙信息广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_CONNECTED);
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);
        filter.addAction(BleService.ACTION_CONNECTING_FAIL);
        mBleReceiver = new BleReceiver();
        registerReceiver(mBleReceiver, filter);
    }
    /**
     * 服务
     */
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mBleService = ((BleService.LocalBinder) rawBinder).getService();
        }

        public void onServiceDisconnected(ComponentName classname) {
            mBleService = null;
        }
    };
    /**
     * 蓝牙信息接收器
     */
    private class BleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }
            switch (action) {
                case BleService.ACTION_GATT_CONNECTED:
                    Toast.makeText(MainActivity.this, "蓝牙已连接", Toast.LENGTH_SHORT).show();
//                    if(0==state){
//
//                    }
//                    byte[] sendData = ByteUtils.packageSendDataNew("01",0,0,0,0,0,0);
//                    //System.out.println(ByteUtils.byteArrayToHexString(ByteUtils.packageSendData(1,0,0,0,0)));
//                   //Log.i("mian", "加密数据123：" +  ByteUtils.getString(ByteUtils.getChars("ST12345678\r\n".getBytes("UTF-16"))));
////                    Log.i("main","解密数据："+ByteUtils.decryp("01",passwordData));
//                    Toast.makeText(MainActivity.this, "发送数据："+ByteUtils.byteArrayToHexString(ByteUtils.packageSendDataNew("01",0,0,0,0,0,0)), Toast.LENGTH_SHORT).show();
//                    mBleService.sendData(sendData);
                    isWrite = false;

                    break;

                case BleService.ACTION_GATT_DISCONNECTED:
                    Toast.makeText(MainActivity.this, "蓝牙已断开", Toast.LENGTH_SHORT).show();
                    mBleService.release();
                    break;

                case BleService.ACTION_GATT_SERVICES_DISCOVERED:
                    Toast.makeText(MainActivity.this, "发现服务了", Toast.LENGTH_SHORT).show();
                    mBleService.setBleNotification();
//                    byte[] sendData = ByteUtils.packageSendDataNew("01",0,0,0,0,0,0);
//                    //System.out.println(ByteUtils.byteArrayToHexString(ByteUtils.packageSendData(1,0,0,0,0)));
//                    //Log.i("mian", "加密数据123：" +  ByteUtils.getString(ByteUtils.getChars("ST12345678\r\n".getBytes("UTF-16"))));
////                    Log.i("main","解密数据："+ByteUtils.decryp("01",passwordData));
//                    Toast.makeText(MainActivity.this, "发送数据："+ByteUtils.byteArrayToHexString(ByteUtils.packageSendDataNew("01",0,0,0,0,0,0)), Toast.LENGTH_SHORT).show();
//                    mBleService.sendData(sendData);
//                    isWrite = false;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                
                                try {
                                    Thread.sleep(4000);
                                    byte[] sendData = ByteUtils.packageSendDataNew("01",0,0,0,0,0,0);
                                    //System.out.println(ByteUtils.byteArrayToHexString(ByteUtils.packageSendData(1,0,0,0,0)));
                                    //Log.i("mian", "加密数据123：" +  ByteUtils.getString(ByteUtils.getChars("ST12345678\r\n".getBytes("UTF-16"))));
//                    Log.i("main","解密数据："+ByteUtils.decryp("01",passwordData));
                                    //Toast.makeText(MainActivity.this, "发送数据："+ByteUtils.byteArrayToHexString(ByteUtils.packageSendDataNew("01",0,0,0,0,0,0)), Toast.LENGTH_SHORT).show();
                                    mBleService.sendData(sendData);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        
                    }).start();
                    break;

                case BleService.ACTION_CONNECTING_FAIL:
                    Toast.makeText(MainActivity.this, "蓝牙已断开", Toast.LENGTH_SHORT).show();
                    mBleService.disconnect();
                    break;

                case BleService.ACTION_DATA_AVAILABLE:
                    byte[] data = intent.getByteArrayExtra(BleService.EXTRA_DATA);
                    try {
                        String text = ByteUtils.byteArrayToHexString(data);
                        //Toast.makeText(MainActivity.this, "接收到的数据:"+text, Toast.LENGTH_LONG).show();
                        if(!ByteUtils.isNormalDate(text)){
                            Toast.makeText(MainActivity.this, "数据格式不正确，请检查数据！", Toast.LENGTH_LONG).show();
                        }
                        //Toast.makeText(MainActivity.this, "收到数据："+text, Toast.LENGTH_LONG).show();
                        String controlStr =  ByteUtils.getControlStr(text);
                        switch (controlStr){
                            case "12": //返回数据
                                isWrite = false;
                                Toast.makeText(MainActivity.this, "设置成功！", Toast.LENGTH_SHORT).show();
	                            //Toast.makeText(MainActivity.this, "设置成功接收的控制str："+text, Toast.LENGTH_LONG).show();
                                if(!isWrite) {
                                    //开闭环控制值
                                    String ctrlStr = String.valueOf(Integer.valueOf(ByteUtils.getContorlValueStr(text),16));
                                    Log.i(this.toString(), "控制返回值"+ctrlStr);
                                    if(ctrlStr.equals("0")){
                                        radioGroup.check(closedLoop.getId());
                                        closeOutputRatioValue = Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16);
                                    }else{
                                        radioGroup.check(openLoop.getId());
                                        openOutputRatioValue = Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16);
                                    }
                                    //输出比例
                                    float outputRatioValue = ((float) Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16)) / 100;
                                    outputRatioView.setText(String.valueOf(outputRatioValue));
                                    barOutputRatio.setProgress(Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16)- 80);
                                    if(ctrlStr.equals("0")) {
                                        //时间
                                        timeValue = Integer.valueOf(ByteUtils.getParamVale("time", text), 16);
                                        timeTextView.setText(String.valueOf(timeValue));
                                        barTime.setProgress(timeValue);
                                        //上升误差
                                        risingError = Integer.valueOf(ByteUtils.getParamVale("rising_error", text), 16);
                                        risingErrorValue.setText(String.valueOf(risingError));
                                        barRisingError.setProgress(risingError);
                                        //下降误差
                                        descentError = Integer.valueOf(ByteUtils.getParamVale("descent_error", text), 16);
                                        descentErrorValue.setText(String.valueOf(descentError));
                                        barDescentError.setProgress(descentError);
                                        //采样时间
                                        sampleTime = Integer.valueOf(ByteUtils.getParamVale("sample_time", text), 16);
                                        sampleTimeValue.setText(String.valueOf(sampleTime));
                                        barSampleTime.setProgress(sampleTime);
                                    }
                                    isWrite = true;
                                }
                                //currentView.setText(valueStr);
                                break;
                            case "AA": //输入、输出电压
                                //Toast.makeText(MainActivity.this, "AA接收电压控制str："+text, Toast.LENGTH_LONG).show();
                                Log.i(this.toString(),"AA接收电压控制str："+ text);
                                String input = String.valueOf(Integer.valueOf(ByteUtils.getInputValue(text),16));
                                BigDecimal inputV =  new BigDecimal(input).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
                                inputValue.setText(inputV.toString()+"kpa");
                                String output =String.valueOf(Integer.valueOf(ByteUtils.getOutValue(text),16));
                                BigDecimal outputV =  new BigDecimal(output).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
                                outputValue.setText(outputV.toString()+"kpa");
                                break;

                            case "14": //返回控制值
                                String ctrlStr = ByteUtils.getContorlValueStr(text);
                                Log.i(this.toString(), "控制返回值"+ctrlStr);
                                if(ctrlStr.equals("0")){
                                    radioGroup.check(closedLoop.getId());
                                }else{
                                    radioGroup.check(openLoop.getId());
                                }
                                break;
                            case "11":
                                Toast.makeText(MainActivity.this, "连接成功！", Toast.LENGTH_SHORT).show();
	                            //Toast.makeText(MainActivity.this, "连接成功接收的控制str："+text, Toast.LENGTH_LONG).show();
                                //开闭环控制值
                                String ctrlStr1 = String.valueOf(Integer.valueOf(ByteUtils.getContorlValueStr(text),16));
                                Log.i(this.toString(), "控制返回值"+ctrlStr1);
                                if(ctrlStr1.equals("0")){
                                    radioGroup.check(closedLoop.getId());
                                }else{
                                    radioGroup.check(openLoop.getId());
                                }
                                //输出比例
                                //开环数据
                                openOutputRatioValue = Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16);
                                closeOutputRatioValue = Integer.valueOf(ByteUtils.getParamVale("close",text), 16);
                                float outputRatioValue = 1;
                                if(ctrlStr1.equals("0")) {
                                    outputRatioValue = ((float) closeOutputRatioValue) / 100;
                                    barOutputRatio.setProgress(closeOutputRatioValue- 80);
                                }else{
                                    outputRatioValue = ((float) openOutputRatioValue) / 100;
                                    barOutputRatio.setProgress(openOutputRatioValue- 80);
                                }
                                outputRatioView.setText(String.valueOf(outputRatioValue));

                                //时间
                                timeValue = Integer.valueOf(ByteUtils.getParamVale("time", text), 16);
                                //上升误差
                                risingError = Integer.valueOf(ByteUtils.getParamVale("rising_error", text), 16);
                                //下降误差
                                descentError = Integer.valueOf(ByteUtils.getParamVale("descent_error", text), 16);
                                //采样时间
                                sampleTime = Integer.valueOf(ByteUtils.getParamVale("sample_time", text), 16);
                                if(ctrlStr1.equals("0")) {
                                    
                                    timeTextView.setText(String.valueOf(timeValue));
                                    barTime.setProgress(timeValue);
                                   
                                    risingErrorValue.setText(String.valueOf(risingError));
                                    barRisingError.setProgress(risingError);
                                    
                                    descentErrorValue.setText(String.valueOf(descentError));
                                    barDescentError.setProgress(descentError);
                                   
                                    sampleTimeValue.setText(String.valueOf(sampleTime));
                                    barSampleTime.setProgress(sampleTime);
                                }
                                isWrite = false;
                                break;
                            case "13":
                                if(!isWrite) {
                                    //输出比例
                                    float outputRatioValue1 = ((float) Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16)) / 100;
                                    outputRatioView.setText(String.valueOf(outputRatioValue1));
                                    barOutputRatio.setProgress(Integer.valueOf(ByteUtils.getParamVale("output_ratio",text), 16)- 80);
                                    //时间
                                     timeValue =  Integer.valueOf(ByteUtils.getParamVale("time",text),16);
                                    timeTextView.setText(String.valueOf(timeValue));
                                    barTime.setProgress(timeValue);
                                    //上升误差
                                     risingError = Integer.valueOf(ByteUtils.getParamVale("rising_error",text),16);
                                    risingErrorValue.setText(String.valueOf(risingError));
                                    barRisingError.setProgress(risingError);
                                    //下降误差
                                     descentError = Integer.valueOf(ByteUtils.getParamVale("descent_error",text),16);
                                    descentErrorValue.setText(String.valueOf(descentError));
                                    barDescentError.setProgress(risingError);
                                    //采样时间
                                     sampleTime = Integer.valueOf(ByteUtils.getParamVale("sample_time",text),16);
                                    sampleTimeValue.setText(String.valueOf(sampleTime));
                                    barDescentError.setProgress(risingError);
                                    isWrite = true;
                                }
                                break;
//                             case "12":
//                                 isWrite = false;
//                                 Toast.makeText(MainActivity.this, "设置成功！", Toast.LENGTH_SHORT).show();
//                                 break;
                            default:
                                break;
                        }

                        Log.i("蓝牙", "收到的数据123：" + text);


                    }catch (Exception e){
                        Log.i("蓝牙",e.getMessage());
                    }
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                // 直接连接蓝牙设备
                scanBleDevice();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBleReceiver != null) {
            unregisterReceiver(mBleReceiver);
            mBleReceiver = null;
        }
        if(mServiceConnection != null) {
            unbindService(mServiceConnection);
            mServiceConnection = null;
        }
        if(mBleService != null) {
            unregisterReceiver(mBleReceiver);
            mBleService = null;
        }
        state=0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //输出比例
            case R.id.bar_output_ratio_sub:
                Log.i("this","点击-了！");
                // seekBarKk1.set
                SeekBarUtil.sub(barOutputRatio,1,80,outputRatioView,1,false);
                break;
            case R.id.bar_output_ratio_plus:
               Log.i("this","点击+了！");
               SeekBarUtil.plus(barOutputRatio,1,outputRatioView,1,false);
               break;
               //时间（延时）
            case R.id.bar_time_sub:
                Log.i("this","点击-了！");
                SeekBarUtil.sub(barTime,1,0,timeTextView,2,true);
                break;
            case R.id.bar_time_plus:
                Log.i("this","点击+了！");
                SeekBarUtil.plus(barTime,1,timeTextView,2,true);
                break;
                //上升误差
            case R.id.bar_rising_sub:
                Log.i("this","点击-了！");
                SeekBarUtil.sub(barRisingError,1,0,risingErrorValue,2,false);
                break;
            case R.id.bar_rising_plus:
                Log.i("this","点击+了！");
                SeekBarUtil.plus(barRisingError,1,risingErrorValue,2,false);
                break;
                //下降误差
            case R.id.bar_descent_sub:
                Log.i("this","点击-了！");
                SeekBarUtil.sub(barDescentError,1,0,descentErrorValue,2,false);
                break;
            case R.id.bar_descent_plus:
                Log.i("this","点击+了！");
                SeekBarUtil.plus(barDescentError,1,descentErrorValue,2,false);
                break;
                //采样时间
            case R.id.bar_sample_time_sub:
                Log.i("this","点击-了！");
                SeekBarUtil.sub(barSampleTime,1,0,sampleTimeValue,2,true);
                break;
            case R.id.bar_sample_time_plus:
                Log.i("this","点击+了！");
                SeekBarUtil.plus(barSampleTime,1,sampleTimeValue,2,true);
                break;
            case R.id.connect:
                String connectStr = connectEditText.getText().toString();
                Log.i("mian", "输入串：" + connectStr);
                if(TextUtils.isEmpty(connectStr)){
                    Toast.makeText(MainActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!"20190905".equals(connectStr)){
                    Toast.makeText(MainActivity.this, "密码不正确！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(MainActivity.this, "密码验证成功！", Toast.LENGTH_SHORT).show();
                isWrite = false;
                state = 1;
                connect.setBackgroundColor(Color.parseColor("#00FF00"));
//                try {
//                    byte[] sendData = ByteUtils.packageSendData(1,0,0,0,0);
//                    //System.out.println(ByteUtils.byteArrayToHexString(ByteUtils.packageSendData(1,0,0,0,0)));
//                   //Log.i("mian", "加密数据123：" +  ByteUtils.getString(ByteUtils.getChars("ST12345678\r\n".getBytes("UTF-16"))));
////                    Log.i("main","解密数据："+ByteUtils.decryp("01",passwordData));
//                    mBleService.sendData(sendData);
//                    isWrite = false;
//
//
//                }catch (Exception e){
//                    //System.out.println(e.getMessage());
//                    Log.e("发送数据：",e.getStackTrace().toString());
//                }

                break;
            case R.id.confirm:
                try {
                    //Toast.makeText(MainActivity.this, "密码连接状态:"+state, Toast.LENGTH_LONG).show();
                    if(0==state){
                        Toast.makeText(MainActivity.this, "请输入密码连接！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //组装发送控制的数据

                    int outputRatio = barOutputRatio.getProgress()+80;
                    int time = barTime.getProgress();
                    int risingError = barRisingError.getProgress();
                    int descentError = barDescentError.getProgress();
                    int sampleTime = barSampleTime.getProgress();
                    //byte[] setData = ByteUtils.packageSendDataNew("02",outputRatio,time,risingError,descentError,sampleTime,0);
                    if(loop == null){
                        Toast.makeText(MainActivity.this, "请选择开闭环控制！", Toast.LENGTH_SHORT).show();
                    }
                    byte[] sendCtlDate = ByteUtils.packageSendDataNew("04",Integer.valueOf(loop),outputRatio,time,risingError,descentError,sampleTime);

                    //System.out.println(ByteUtils.byteArrayToHexString(setData));
                    mBleService.sendData(sendCtlDate);
                    //mBleService.sendData(setData);
                    isWrite = false;
                }catch (Exception e){
                    Log.i("main_error",e.getMessage());
                }
                break;
            case R.id.cancle:
                barOutputRatio.setProgress(20);
                outputRatioView.setText("1");

                barTime.setProgress(0);
                timeTextView.setText("0");

                risingErrorValue.setText("0");
                barRisingError.setProgress(0);

                descentErrorValue.setText("0");
                barDescentError.setProgress(0);

                sampleTimeValue.setText("0");
                barSampleTime.setProgress(0);

                isWrite = false;
                break;
            case R.id.search:
                // 搜索蓝牙设备
                scanBleDevice();
                // 初始化数据
                initData();
                // 注册蓝牙信息接收器
                registerBleReceiver();
                break;

        }

    }
    public void local(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时
            //判断是否具有权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要向用户解释为什么需要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    Toast.makeText(MainActivity.this,"需要打开位置权限才可以搜索到Ble设备", Toast.LENGTH_SHORT).show();
                }
                //请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        REQUEST_CODE_ACCESS_COARSE_LOCATION);
            }
        }
    }
}
